#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/7/1 16:03
# @Author : wn 
# @File: search_page.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡
import datetime
from operator import itemgetter

from django.forms.models import model_to_dict
from django.http import JsonResponse

from trade.model_choices import *
from trade.models import *


def searchs_live(stgid_search=None, stgname_search=None, packstatus_search=None, auditstatus_search=None,
                 stgrunstatus_search=None, type=None, **kwargs):
    search_list = []
    customerid = kwargs.get("customerid") if kwargs else ""
    search_type = kwargs.get("search_type") if kwargs.get("search_type") else ""
    # 搜索条件 stgname
    if stgname_search != None:
        if stgname_search != '':
            search_list = Liveapproval.objects.using('quantWebDB').all()
            temp_list = []
            for item in search_list:
                stginfo_t = Strategy.objects.using('quantWebDB').filter(stgid=item.stgid).values_list('stgname', )[0]
                stginfo_stgname = list(stginfo_t)[0]
                if stgname_search in stginfo_stgname:
                    temp_list.append(item)
            search_list = temp_list
        else:
            search_list = list(Liveapproval.objects.using('quantWebDB').all())

    # 搜索条件 stgid
    if stgid_search != None:
        if stgid_search != '':
            if len(search_list) != 0:
                temp_list = []
                for item in search_list:
                    if stgid_search in str(item.stgid):
                        temp_list.append(item)
                search_list = temp_list

    # 搜索条件 packstatus_search
    if packstatus_search != None:
        if packstatus_search != "":
            if len(search_list) != 0:
                temp_list = []
                for item in search_list:
                    if item.packstatus == packstatus_search:
                        temp_list.append(item)
                search_list = temp_list

    # 搜索条件 auditstatus
    if auditstatus_search != None:
        if auditstatus_search != '':
            if len(search_list) != 0:
                temp_list = []
                for item in search_list:
                    if item.auditstatus == auditstatus_search:
                        temp_list.append(item)
                search_list = temp_list

    # 搜索条件 stgrunstatus_search
    if stgrunstatus_search != None:
        if stgrunstatus_search != "":
            if len(search_list) != 0:
                temp_list = []
                for item in search_list:
                    runstatus_list_tuple = Liverun.objects.using('quantWebDB').filter(stgid=item.stgid).values_list('runstatus')
                    if len(runstatus_list_tuple) != 0:
                        stgrunstatus_filter = list(runstatus_list_tuple[0])[0]
                        if stgrunstatus_search == stgrunstatus_filter:
                            temp_list.append(item)
                search_list = temp_list
    if type == 'livePackList':
        if len(search_list) != 0:
            temp_list = []
            for item in search_list:
                # 新增一个backtype属性，记录主/备服务器，传给前端。(liu 20200805)
                env_qs = Environment.objects.using('quantWebDB').filter(envid=item.envid)
                if len(env_qs) != 0:
                    item.backtype = BackType.get(env_qs[0].backtype)
                if item.auditstatus == '3':
                    temp_list.append(item)
            search_list = temp_list

    if type == 'liveList':
        if len(search_list) != 0:
            temp_list = []
            for item in search_list:
                qs = Strategy.objects.using('quantWebDB').filter(stgid=item.stgid)
                env_qs = Environment.objects.using('quantWebDB').filter(envid=item.envid)
                # 都打包成功显示到实盘审批表
                laPS_qs = Liveapproval.objects.using('quantWebDB').filter(stgid=item.stgid)
                flagPackStatus = True
                for lapsObj in laPS_qs:
                    if lapsObj.auditstatus == "3" and lapsObj.packstatus != "1":
                        flagPackStatus = False

                if len(env_qs) != 0:
                    # 实盘列表查询也要赋值属性，不然会报错(liu 20200805)
                    envBackType = env_qs[0].backtype
                    item.backtype = BackType.get(envBackType)
                    for stg in qs:
                        if stg.liveisdelete != 0 and item.auditstatus == '3' and item.packstatus == '1' and envBackType == "1" and flagPackStatus:
                            temp_list.append(item)
            search_list = temp_list

    result_list = []
    # 策略表
    for item in search_list:
        result_dict = {}
        result_dict['stgid'] = item.stgid
        result_dict['envid'] = item.envid
        result_dict['remark'] = item.remark
        result_dict['audittime'] = item.audittime
        result_dict['inserttime'] = item.inserttime
        result_dict['auditstatus'] = AuditStatus.get(item.auditstatus, None)
        result_dict['auditmsg'] = item.auditmsg
        result_dict['packstatus'] = PackStatus_ModelChoices.get(item.packstatus, None)
        result_dict['packmsg'] = item.packmsg
        result_dict['packtime'] = item.packtime

        # 实盘审批成功会查一次，type没有对应的livepacklist或livelist,所以取backtype属性会报错，这里需要先判断一下(liu 20200805)
        result_dict['backtype'] = item.backtype if hasattr(item, "backtype") else ""

        # 策略表中的：策略名称，上传时间
        stginfo_list = list(Strategy.objects.using('quantWebDB').filter(stgid=item.stgid))
        if len(stginfo_list) != 0:
            result_dict['stgname'] = stginfo_list[0].stgname
            result_dict['createtime'] = stginfo_list[0].createtime
            result_dict['stggroup'] = stginfo_list[0].stggroup
            result_dict['isopr'] = "0"
            if customerid == stginfo_list[0].customerid:
                result_dict['isopr'] = "1"

        # 环境表中的：服务器（envname+ip)
        envinfo_list = list(Environment.objects.using('quantWebDB').filter(envid=item.envid))
        if len(envinfo_list) != 0:
            result_dict['envname'] = envinfo_list[0].envname + "(" + envinfo_list[0].ip + ")"

        # 操作value
        result_dict['approval_option'] = item.stgid  # 上传列表
        result_dict['poption'] = str(item.stgid) + "_" + str(item.envid)  # 打包列表
        result_dict['loption'] = item.stgid  # 实盘列表

        result_list.append(result_dict)

        # 实盘运行表
        liverun_list = list(Liverun.objects.using('quantWebDB').filter(stgid=item.stgid))
        if liverun_list is not None and len(liverun_list) != 0:
            result_dict['starttime'] = liverun_list[0].starttime
            result_dict['endtime'] = liverun_list[0].endtime
            result_dict['runstatus'] = StgRunStatus.get(liverun_list[0].runstatus, None)

        # 操作value
        result_dict['approval_option'] = item.stgid

        # 排序
    for item in result_list:
        if (item.get('stgid') is None):
            item['stgid'] = '-1'
    result_list_sorted = sorted(result_list, key=itemgetter('stgid'), reverse=True)
    if search_type:
        ## 定义两个列表，一个存待审批，另一个存其他审批状态。
        prestatus_list = []
        othstatus_list = []

        for i in range(len(result_list_sorted)):
            if result_list_sorted[i].get("auditstatus") == "待审批":
                prestatus_list.append(result_list_sorted[i])
            else:
                othstatus_list.append(result_list_sorted[i])
        prestatus_list.extend(othstatus_list)
        result_list_sorted = prestatus_list
    return JsonResponse(result_list_sorted, safe=False)


def searchs_paper(stgid_search=None, stgname_search=None, auditstatus_search=None, packstatus_search=None,
                  stgrunstatus_search=None, type=None, **kwargs):
    search_list = []
    customerid = kwargs.get("customerid") if kwargs.get("customerid") else ""
    search_type = kwargs.get("search_type") if kwargs.get("search_type") else ""
    # 搜索条件 stgname
    if stgname_search != None:
        if stgname_search != '':
            search_list = Strategy.objects.using('quantWebDB').filter(stgname__icontains=stgname_search)
        else:
            search_list = list(Strategy.objects.using('quantWebDB').all())

    # 搜索条件 stgid
    if stgid_search != None:
        if stgid_search != '':
            if len(search_list) != 0:
                temp_list = []
                for item in search_list:
                    if stgid_search in str(item.stgid):
                        temp_list.append(item)
                search_list = temp_list

    # 搜索条件 auditstatus
    if auditstatus_search != None:
        if auditstatus_search != '':
            if len(search_list) != 0:
                temp_list = []
                for item in search_list:
                    auditstatus_list_tuple = Paperapproval.objects.using('quantWebDB').filter(stgid=item.stgid).values_list(
                        'auditstatus')
                    if len(auditstatus_list_tuple) != 0:
                        auditstatus_filter = list(auditstatus_list_tuple[0])[0]
                        if auditstatus_filter == auditstatus_search:
                            temp_list.append(item)
                search_list = temp_list

    # 搜索条件 packstatus_search
    if packstatus_search != None:
        if packstatus_search != "":
            if len(search_list) != 0:
                temp_list = []
                for item in search_list:
                    aa = item.stgid
                    packstatus_list_tuple = Paperapproval.objects.using('quantWebDB').filter(stgid=item.stgid)
                    bb = len(packstatus_list_tuple)
                    if len(packstatus_list_tuple) != 0:
                        for psf in packstatus_list_tuple:
                            cc = psf.stgid
                            packstatus_filter = psf.packstatus
                            if packstatus_filter == packstatus_search:
                                temp_list.append(item)
                search_list = temp_list

    # 搜索条件 stgrunstatus_search
    if stgrunstatus_search != None:
        if stgrunstatus_search != "":
            if len(search_list) != 0:
                temp_list = []
                for item in search_list:
                    runstatus_list_tuple = Paperrun.objects.using('quantWebDB').filter(stgid=item.stgid).values_list('runstatus')
                    if len(runstatus_list_tuple) != 0:
                        stgrunstatus_filter = list(runstatus_list_tuple[0])[0]
                        if stgrunstatus_search == stgrunstatus_filter:
                            temp_list.append(item)
                search_list = temp_list
    if type == 'packList':
        if len(search_list) != 0:
            temp_list = []
            for item in search_list:
                a = item.stgid
                auditstatus_list_tuple = Paperapproval.objects.using('quantWebDB').filter(stgid=item.stgid)

                if len(auditstatus_list_tuple) != 0:
                    for pas in auditstatus_list_tuple:
                        auditstatus_filter = pas.auditstatus
                        if packstatus_search:
                            if auditstatus_filter == '3' and pas.packstatus == packstatus_search:
                                if item not in temp_list:
                                    temp_list.append(item)
                        else:
                            if auditstatus_filter == '3':
                                if item not in temp_list:
                                    temp_list.append(item)

            search_list = temp_list

    if type == 'paperList':
        if len(search_list) != 0:
            temp_list = []
            for item in search_list:
                flag_packstatus = True
                list_tuple = Paperapproval.objects.using('quantWebDB').filter(stgid=item.stgid).values_list(
                    'auditstatus', 'packstatus')
                if len(list_tuple) != 0:
                    for item_a_p in list_tuple:
                        iapList = list(item_a_p)
                        if len(iapList) == 2:  # 永==2
                            if iapList[1] != '1':
                                flag_packstatus = False
                    auditstatus_filter = list(list_tuple[0])[0]
                    # packstatus_filter = list(list_tuple[0])[1]
                    if auditstatus_filter == '3' and flag_packstatus and item.paperisdelete != 0:
                        temp_list.append(item)
            search_list = temp_list

    result_list = []
    # 打包列表的[]
    item_approval_pack_list = []

    # 策略表
    for item in search_list:
        result_dict = {}
        result_dict['stgid'] = item.stgid
        result_dict['stgname'] = item.stgname
        result_dict['createtime'] = item.createtime
        result_dict['backupdatetime'] = item.backupdatetime
        result_dict['backtest'] = item.backtest
        result_dict['status'] = item.status
        result_dict['stgfile'] = item.stgfile
        result_dict['stggroup'] = item.stggroup
        result_dict['paperisdelete'] = item.paperisdelete
        result_dict['customerid'] = item.customerid
        result_dict['isopr'] = "0"
        if customerid == item.customerid:
            result_dict['isopr'] = "1"
        # 仿真策略审批表
        paperapp_list = list(Paperapproval.objects.using('quantWebDB').filter(stgid=item.stgid))
        if paperapp_list is not None and len(paperapp_list) != 0:
            result_dict['auditstatus'] = AuditStatus.get(paperapp_list[0].auditstatus, None)
            result_dict['updatetime'] = paperapp_list[0].updatetime
            result_dict['auditmsg'] = paperapp_list[0].auditmsg
            # result_dict['packstatus'] = PackStatus_ModelChoices.get(paperapp_list[0].packstatus, None)
            # result_dict['packmsg'] = paperapp_list[0].packmsg
            # result_dict['packtime'] = paperapp_list[0].packtime

            # 打包列表的[]
            for item_approval_packstatus in paperapp_list:
                item_approval_pack_dict = {}
                item_approval_pack_dict['stgid'] = item.stgid
                item_approval_pack_dict['stgname'] = item.stgname
                item_approval_pack_dict['packstatus'] = PackStatus_ModelChoices.get(item_approval_packstatus.packstatus,
                                                                                    None)
                item_approval_pack_dict['packmsg'] = item_approval_packstatus.packmsg
                item_approval_pack_dict['packtime'] = item_approval_packstatus.packtime
                envObj = Environment.objects.using('quantWebDB').filter(envid=item_approval_packstatus.envid)[0]
                item_approval_pack_dict['envname'] = envObj.envname
                item_approval_pack_dict['backtype'] = BackType.get(envObj.backtype, None)
                item_approval_pack_dict['poption'] = str(item.stgid) + "_" + str(item_approval_packstatus.envid)  # 打包列表
                item_approval_pack_dict['isopr'] = result_dict['isopr']
                if packstatus_search:
                    if item_approval_packstatus.auditstatus == "3" and packstatus_search == item_approval_packstatus.packstatus:
                        item_approval_pack_list.append(item_approval_pack_dict)
                else:
                    if item_approval_packstatus.auditstatus == "3":
                        item_approval_pack_list.append(item_approval_pack_dict)

        # 仿真运行表
        paperrun_list = list(Paperrun.objects.using('quantWebDB').filter(stgid=item.stgid))
        if paperrun_list is not None and len(paperrun_list) != 0:
            result_dict['starttime'] = paperrun_list[0].starttime
            result_dict['endtime'] = paperrun_list[0].endtime
            result_dict['runstatus'] = StgRunStatus.get(paperrun_list[0].runstatus, None)
        # 策略在实盘审批表中的状态
        result_dict['aud_status_live'] = '-1.1'
        status_live_len = Liveapproval.objects.using('quantWebDB').filter(stgid=item.stgid)
        if len(status_live_len) > 0:
            auditstatus_tuple = status_live_len.values_list('auditstatus')[0]
            aud_status_live = list(auditstatus_tuple)[0]
            result_dict['aud_status_live'] = aud_status_live

        # my_columns，操作的field 的值
        result_dict['uoption'] = item.stgid  # 上传列表
        # result_dict['poption'] = str(item.stgid) + "_"  # 打包列表
        result_dict['soption'] = item.stgid  # 仿真列表
        result_dict['approval_option'] = item.stgid  # 仿真策略审批
        if type == 'packList':
            result_list = item_approval_pack_list
        else:
            result_list.append(result_dict)
    # 排序
    for item in result_list:
        if (item.get('stgid') is None):
            item['stgid'] = '-1'
    result_list_sorted = sorted(result_list, key=itemgetter('stgid'), reverse=True)
    if search_type:
        ## 定义两个列表，一个存待审批，另一个存其他审批状态。
        prestatus_list = []
        othstatus_list = []

        for i in range(len(result_list_sorted)):
            if result_list_sorted[i].get("auditstatus") == "待审批":
                prestatus_list.append(result_list_sorted[i])
            else:
                othstatus_list.append(result_list_sorted[i])
        prestatus_list.extend(othstatus_list)
        result_list_sorted = prestatus_list
    return JsonResponse(result_list_sorted, safe=False)


def search_enviro(envname=None, ip=None, type=None):
    search_obj = Environment.objects.using('quantWebDB').all()
    # 搜索条件 envname
    if envname != None:
        if envname != '':
            search_obj = search_obj.filter(envname__icontains=envname)

    # 搜索条件 ip
    if ip != None:
        if ip != '':
            search_obj = search_obj.filter(ip__contains=ip)
    # 搜索条件 type
    if type != None:
        if type != '':
            search_obj = search_obj.filter(type=type)

    result_list = []
    # 策略表
    for item in search_obj:
        result_dict = {}
        result_dict['envid'] = item.envid
        result_dict['envname'] = item.envname
        result_dict['ip'] = item.ip
        result_dict['updatetime'] = item.updatetime
        result_dict['type'] = EnvType.get(item.type, None)
        result_dict['backtype'] = BackType.get(item.backtype, None)
        result_dict['runpath'] = item.runpath
        result_dict['remark'] = item.remark

        # 操作
        result_dict['eoption'] = item.envid
        result_list.append(result_dict)
        # 排序
    for item in result_list:
        if (item.get('envid') is None):
            item['envid'] = '-1'
    result_list_sorted = sorted(result_list, key=itemgetter('envid'), reverse=True)
    return JsonResponse(result_list_sorted, safe=False)


def search_log(customerid=None, envir=None, optinfo=None, optfunction=None, type=None, logLevel=None, dateTime=None,
               stgname=None, stgid=None):
    # 操作日志
    result_list_sorted = []
    result_list = []
    if type == '0':
        search_obj = Operationlog.objects.using('quantWebDB').all()
        # 搜索条件 envname
        if customerid != None:
            if customerid != '':
                search_obj = search_obj.filter(customerid__icontains=customerid)

        # 搜索条件 ip
        if optinfo != None:
            if optinfo != '':
                search_obj = search_obj.filter(optinfo__icontains=optinfo)
        # 搜索条件 type
        if optfunction != None:
            if optfunction != '':
                search_obj = search_obj.filter(optfunction=optfunction)

        # 日志表
        for item in search_obj:
            result_dict = {}
            result_dict['sequenceno'] = item.sequenceno
            result_dict['customerid'] = item.customerid
            result_dict['modular'] = item.modular
            result_dict['optfunction'] = LogContent.get(item.optfunction, None)
            result_dict['optinfo'] = item.optinfo
            result_dict['opttime'] = item.opttime
            result_list.append(result_dict)
        # 排序
        for item in result_list:
            if (item.get('sequenceno') is None):
                item['sequenceno'] = '-1'
        result_list_sorted = sorted(result_list, key=itemgetter('sequenceno'), reverse=True)
    # 策略日志
    elif type == '1':
        # 策略日志表
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        # 如果是仿真环境
        if envir == "1":
            stgLogList = list(Rulemessage.objects.using("quantPaperDB").all())
        elif envir == "2":
            stgLogList = list(Rulemessage.objects.using("quantLiveDB").all())
        else:
            stgLogList = []

        # 日志级别 char
        if logLevel != None:
            if logLevel != "":
                temp_list = []
                for item in stgLogList:
                    if item.messagelevel == logLevel:
                        temp_list.append(item)
                stgLogList = temp_list
        # 时间 char
        if dateTime != None:
            if dateTime != "":
                temp_list = []
                for item in stgLogList:
                    a = item.timestamp
                    if dateTime in item.timestamp:
                        temp_list.append(item)
                stgLogList = temp_list
        # 策略id int
        if stgid != None:
            if stgid != "":
                temp_list = []
                for item in stgLogList:
                    if stgid in str(item.ruleid):
                        temp_list.append(item)
                stgLogList = temp_list

        # 策略名称 char
        if stgname != None:
            if stgname != "":
                temp_list = []
                for item in stgLogList:
                    stg_qs = Strategy.objects.using('quantWebDB').filter(stgid=item.ruleid)
                    if len(stg_qs) != 0:
                        if stgname in stg_qs[0].stgname:
                            temp_list.append(item)
                stgLogList = temp_list

        for item in stgLogList:
            result_dict = {}
            result_dict['timestamp'] = item.timestamp
            result_dict['ruleid'] = item.ruleid
            # 策略名
            stg_qs = Strategy.objects.using('quantWebDB').filter(stgid=item.ruleid)
            stgname = ''
            if len(stg_qs) != 0:
                stgname = stg_qs[0].stgname
            result_dict['rulename'] = stgname
            result_dict['messagelevel'] = Stg_LogLevel_ModelChoices.get(item.messagelevel, None)
            result_dict['message'] = item.message
            result_list.append(result_dict)
            # 排序
        for item in result_list:
            if (item.get('timestamp') is None):
                item['timestamp'] = '-1'

        result_list_sorted = sorted(result_list, key=itemgetter('timestamp'), reverse=True)
    return JsonResponse(result_list_sorted, safe=False)


def search_daySearch(instrumentid=None, direction=None, legsettltype=None, tradeid=None, ruleid=None, orderinnerid=None,
                     ordersysid=None, type=None, stgname=None, hisStartTime=None, hisEndTime=None, bondid=None,
                     customerid=None
                     , pflag=None):
    result_list_sorted = []
    today = datetime.datetime.now().strftime("%Y%m%d")
    todayi = datetime.datetime.now().strftime("%Y-%m-%d")
    # 订单 '0'
    ro_obj = Ruleorder.objects.using('quantPaperDB').filter(tradingday=today)
    # 成交 '1'
    rt_obj = Ruletrade.objects.using('quantPaperDB').filter(tradingday=today)
    # 持仓 '2'
    rp_obj = Ruleposition.objects.using('quantPaperDB').filter(tradingday=today)
    # 录入 '3'
    rm_obj = ManualTradePaper.objects.using('quantWebDB').filter(transactime__startswith=todayi)

    # 历史持仓查询，最多查一年的，hisStartTime，hisEndTime
    if hisEndTime != None and hisStartTime != None:
        if hisStartTime != '' and hisEndTime != '':
            endtime = datetime.datetime.strptime(hisEndTime, "%Y-%m-%d")
            starttime = datetime.datetime.strptime(hisStartTime, "%Y-%m-%d")
            if endtime > (starttime + datetime.timedelta(days=366)):
                endtime = starttime + datetime.timedelta(days=366)
            st_str = datetime.datetime.strftime(starttime, '%Y%m%d')
            et_str = datetime.datetime.strftime(endtime, '%Y%m%d')
            rp_obj = Ruleposition.objects.using('quantPaperDB').filter(tradingday__gte=st_str,
                                                                       tradingday__lte=et_str).order_by("ruleid",
                                                                                                        "instrumentid")
        elif hisStartTime and hisEndTime == "":
            starttime = datetime.datetime.strptime(hisStartTime, "%Y-%m-%d")
            st_str = datetime.datetime.strftime(starttime, '%Y%m%d')
            rp_obj = Ruleposition.objects.using('quantPaperDB').filter(tradingday__gte=st_str).order_by("ruleid",
                                                                                                        "instrumentid")
        elif hisStartTime == "" and hisEndTime:
            endtime = datetime.datetime.strptime(hisEndTime, "%Y-%m-%d")
            et_str = datetime.datetime.strftime(endtime, '%Y%m%d')
            rp_obj = Ruleposition.objects.using('quantPaperDB').filter(tradingday__lte=et_str).order_by("ruleid",
                                                                                                        "instrumentid")
        else:
            rp_obj = Ruleposition.objects.using('quantPaperDB').all().order_by("ruleid", "instrumentid")

    if type == '0':
        ro_list = list(ro_obj.values())
        if instrumentid != None:
            if instrumentid != '':
                ro_obj = ro_obj.filter(instrumentid__contains=instrumentid)
                ro_list = ro_obj.values()
        if direction != None:
            if direction != '':
                ro_obj = ro_obj.filter(direction=direction)
                ro_list = ro_obj.values()
        if legsettltype != None:
            if legsettltype != '':
                ro_obj = ro_obj.filter(legsettltype=legsettltype)
                ro_list = ro_obj.values()
        if orderinnerid != None:
            if orderinnerid != '':
                ro_obj = ro_obj.filter(orderinnerid__contains=orderinnerid)
                ro_list = ro_obj.values()
        if ordersysid != None:
            if ordersysid != '':
                ro_obj = ro_obj.filter(ordersysid__contains=ordersysid)
                ro_list = ro_obj.values()
        if ruleid != None:
            if ruleid != '':
                temp_list = []
                for item in ro_obj:
                    if ruleid in str(item["ruleid"]):
                        item_dict = model_to_dict(item)
                        temp_list.append(item_dict)
                ro_list = temp_list

        # 排序 Ruleorder
        for item in ro_list:
            item['legsettltype'] = LegSettlType_ModelChoices.get(item['legsettltype'], None)
            item['direction'] = Direction_ModelChoices.get(item['direction'], None)
            item['reserver1'] = Reserver1_ModelChoices.get(item['reserver1'], None)
            # item['reserver2'] = Reserver2_ModelChoices.get(item['reserver2'], None)
            item['orderstatus'] = OrderStatus_Choices.get(item['orderstatus'], None)
            stg = Strategy.objects.using('quantWebDB').filter(stgid=item["ruleid"])
            if len(stg) != 0:
                stgname = stg[0].stgname
            item['rulename'] = stgname
            if (item.get('orderinnerid') is None):
                item['orderinnerid'] = '-1'
        result_list_sorted = sorted(ro_list, key=itemgetter('orderinnerid'), reverse=True)

    if type == '1':
        rt_list = list(rt_obj.values())
        if instrumentid != None:
            if instrumentid != '':
                rt_obj = rt_obj.filter(instrumentid__contains=instrumentid)
                rt_list = rt_obj.values()
        if direction != None:
            if direction != '':
                rt_obj = rt_obj.filter(direction=direction)
                rt_list = rt_obj.values()
        if legsettltype != None:
            if legsettltype != '':
                rt_obj = rt_obj.filter(legsettltype=legsettltype)
                rt_list = rt_obj.values()
        if tradeid != None:
            if tradeid != '':
                rt_obj = rt_obj.filter(tradeid__contains=tradeid)
                rt_list = rt_obj.values()
        if ruleid != None:
            if ruleid != '':
                temp_list = []
                for item in rt_obj:
                    if ruleid in str(item.ruleid):
                        item_dict = model_to_dict(item)
                        temp_list.append(item_dict)
                rt_list = temp_list

        # 排序 Ruletrade
        for item in rt_list:
            item['legsettltype'] = LegSettlType_ModelChoices.get(item['legsettltype'], None)
            item['direction'] = Direction_ModelChoices.get(item['direction'], None)
            stg = Strategy.objects.using('quantWebDB').filter(stgid=item["ruleid"])
            if len(stg) != 0:
                stgname = stg[0].stgname
            item['rulename'] = stgname
            if (item.get('tradeid') is None):
                item['tradeid'] = '-1'
        result_list_sorted = sorted(rt_list, key=itemgetter('tradeid'), reverse=True)

    if type == '2':
        rp_list = list(rp_obj.values())

        if instrumentid != None:
            if instrumentid != '':
                rp_obj = rp_obj.filter(instrumentid__contains=instrumentid)
                rp_list = rp_obj.values()
        if stgname != None:
            if stgname != '':
                rp_list = []
                for item in rp_obj:
                    rp_dict = {}
                    rp_dict['ruleid'] = item.ruleid
                    rp_dict['position'] = item.position
                    rp_dict['instrumentid'] = item.instrumentid
                    rp_dict['tradingday'] = item.tradingday
                    stg = Strategy.objects.using('quantWebDB').filter(stgid=item.ruleid)
                    if len(stg) != 0:
                        stgname_filter = stg[0].stgname
                        if stgname in stgname_filter:
                            rp_dict['rulename'] = stgname
                            rp_list.append(rp_dict)
        else:
            rp_list = list(rp_obj.values())

        if ruleid != None:
            if ruleid != '':
                temp_list = []
                for item in rp_list:
                    if ruleid in str(item["ruleid"]):
                        temp_list.append(item)
                rp_list = temp_list

        # 排序 Ruleposition
        for item in rp_list:
            stg_qs = Strategy.objects.using('quantWebDB').filter(stgid=item['ruleid'])
            stgname = ''
            if len(stg_qs) != 0:
                stgname = stg_qs[0].stgname
            item['rulename'] = stgname
        if pflag == "2":
            result_list_sorted = sorted(rp_list, key=itemgetter('tradingday'), reverse=True)
        else:
            result_list_sorted = sorted(rp_list, key=itemgetter('ruleid'), reverse=False)

    if type == '3':
        rm_list = list(rm_obj.values())
        if direction is not None:
            if direction != "":
                rm_obj = rm_obj.filter(direction=direction)
                rm_list = rm_obj.values()
        if legsettltype is not None:
            if legsettltype != "":
                rm_obj = rm_obj.filter(settletype=legsettltype)
                rm_list = rm_obj.values()
        if ruleid is not None:
            if ruleid != "":
                temp_list = []
                for item in rm_obj:
                    if ruleid in str(item.ruleid):
                        item_dict = model_to_dict(item)
                        temp_list.append(item_dict)
                rm_list = temp_list
        if bondid is not None:
            if bondid != "":
                temp_list = []
                for item in rm_obj:
                    if bondid in str(item.bondid):
                        item_dict = model_to_dict(item)
                        temp_list.append(item_dict)
                rm_list = temp_list
        if customerid is not None:
            if customerid != "":
                temp_list = []
                for item in rm_obj:
                    if customerid in str(item.customerid):
                        item_dict = model_to_dict(item)
                        temp_list.append(item_dict)
                rm_list = temp_list
        # 排序 Manaual
        for item in rm_list:
            item['settletype'] = LegSettlType_ModelChoices.get(item['settletype'], None)
            item['direction'] = Direction_ModelChoices.get(item['direction'], None)
            stg_qs = Strategy.objects.using('quantWebDB').filter(stgid=item['ruleid'])
            stgname = ''
            if len(stg_qs) != 0:
                stgname = stg_qs[0].stgname
            item['stgname'] = stgname
            if item.get("transactime") is None:
                item["transactime"] = "-1"
        result_list_sorted = sorted(rm_list, key=itemgetter("transactime"), reverse=True)

    return JsonResponse(result_list_sorted, safe=False)


def search_liveSearch(instrumentid=None, direction=None, legsettltype=None, tradeid=None, ruleid=None,
                      orderinnerid=None, ordersysid=None, type=None, stgname=None, hisStartTime=None, hisEndTime=None,
                      bondid=None, customerid=None, pflag=None):
    result_list_sorted = []
    today = datetime.datetime.now().strftime("%Y%m%d")
    todayi = datetime.datetime.now().strftime("%Y-%m-%d")
    # 订单 '0'
    ro_obj = Ruleorder.objects.using('quantLiveDB').filter(tradingday=today)
    # 成交 '1'
    rt_obj = Ruletrade.objects.using('quantLiveDB').filter(tradingday=today)
    # 持仓 '2'
    rp_obj = Ruleposition.objects.using('quantLiveDB').filter(tradingday=today)
    # 录入 '3'
    rm_obj = ManualTradeLive.objects.using('quantWebDB').filter(transactime__startswith=todayi)

    # 历史持仓查询，最多查一年的，hisStartTime，hisEndTime
    if hisEndTime != None and hisStartTime != None:
        if hisStartTime != '' and hisEndTime != '':
            endtime = datetime.datetime.strptime(hisEndTime, "%Y-%m-%d")
            starttime = datetime.datetime.strptime(hisStartTime, "%Y-%m-%d")
            if endtime > (starttime + datetime.timedelta(days=366)):
                endtime = starttime + datetime.timedelta(days=366)
            st_str = datetime.datetime.strftime(starttime, '%Y%m%d')
            et_str = datetime.datetime.strftime(endtime, '%Y%m%d')
            rp_obj = Ruleposition.objects.using('quantLiveDB').filter(tradingday__gte=st_str,
                                                                      tradingday__lte=et_str).order_by(
                "ruleid", "instrumentid")
        elif hisStartTime and hisEndTime == "":
            starttime = datetime.datetime.strptime(hisStartTime, "%Y-%m-%d")
            st_str = datetime.datetime.strftime(starttime, '%Y%m%d')
            rp_obj = Ruleposition.objects.using('quantLiveDB').filter(tradingday__gte=st_str).order_by(
                "ruleid", "instrumentid")
        elif hisStartTime == "" and hisEndTime:
            endtime = datetime.datetime.strptime(hisEndTime, "%Y-%m-%d")
            et_str = datetime.datetime.strftime(endtime, '%Y%m%d')
            rp_obj = Ruleposition.objects.using('quantLiveDB').filter(tradingday__lte=et_str).order_by(
                "ruleid", "instrumentid")
        else:
            rp_obj = Ruleposition.objects.using('quantLiveDB').all().order_by("ruleid", "instrumentid")

    if type == '0':
        ro_list = list(ro_obj.values())
        if instrumentid != None:
            if instrumentid != '':
                ro_obj = ro_obj.filter(instrumentid__contains=instrumentid)
                ro_list = ro_obj.values()
        if direction != None:
            if direction != '':
                ro_obj = ro_obj.filter(direction=direction)
                ro_list = ro_obj.values()
        if legsettltype != None:
            if legsettltype != '':
                ro_obj = ro_obj.filter(legsettltype=legsettltype)
                ro_list = ro_obj.values()
        if orderinnerid != None:
            if orderinnerid != '':
                ro_obj = ro_obj.filter(orderinnerid__contains=orderinnerid)
                ro_list = ro_obj.values()
        if ordersysid != None:
            if ordersysid != '':
                ro_obj = ro_obj.filter(ordersysid__contains=ordersysid)
                ro_list = ro_obj.values()
        if ruleid != None:
            if ruleid != '':
                temp_list = []
                for item in ro_obj:
                    if ruleid in str(item.ruleid):
                        item_dict = model_to_dict(item)
                        temp_list.append(item_dict)
                ro_list = temp_list

        # 排序 Ruleorder

        for item in ro_list:
            item['legsettltype'] = LegSettlType_ModelChoices.get(item['legsettltype'], None)
            item['direction'] = Direction_ModelChoices.get(item['direction'], None)
            item['reserver1'] = Reserver1_ModelChoices.get(item['reserver1'], None)
            # item['reserver2'] = Reserver2_ModelChoices.get(item['reserver2'], None)
            item['orderstatus'] = OrderStatus_Choices.get(item['orderstatus'], None)
            stg = Strategy.objects.using('quantWebDB').filter(stgid=item["ruleid"])
            if len(stg) != 0:
                stgname = stg[0].stgname
            item['rulename'] = stgname
            if (item.get('orderinnerid') is None):
                item['orderinnerid'] = '-1'
        result_list_sorted = sorted(ro_list, key=itemgetter('orderinnerid'), reverse=True)

    if type == '1':
        rt_list = list(rt_obj.values())
        if instrumentid != None:
            if instrumentid != '':
                rt_obj = rt_obj.filter(instrumentid__contains=instrumentid)
                rt_list = rt_obj.values()
        if direction != None:
            if direction != '':
                rt_obj = rt_obj.filter(direction=direction)
                rt_list = rt_obj.values()
        if legsettltype != None:
            if legsettltype != '':
                rt_obj = rt_obj.filter(legsettltype=legsettltype)
                rt_list = rt_obj.values()
        if tradeid != None:
            if tradeid != '':
                rt_obj = rt_obj.filter(tradeid=tradeid)
                rt_list = rt_obj.values()
        if ruleid != None:
            if ruleid != '':
                temp_list = []
                for item in rt_obj:
                    if ruleid in str(item.ruleid):
                        item_dict = model_to_dict(item)
                        temp_list.append(item_dict)
                rt_list = temp_list

        # 排序 Ruletrade
        for item in rt_list:
            item['legsettltype'] = LegSettlType_ModelChoices.get(item['legsettltype'], None)
            item['direction'] = Direction_ModelChoices.get(item['direction'], None)
            stg = Strategy.objects.using('quantWebDB').filter(stgid=item["ruleid"])
            if len(stg) != 0:
                stgname = stg[0].stgname
            item['rulename'] = stgname
            if (item.get('tradetime') is None):
                item['tradetime'] = '-1'
        result_list_sorted = sorted(rt_list, key=itemgetter('tradetime'), reverse=True)

    if type == '2':
        rp_list = list(rp_obj.values())

        if instrumentid != None:
            if instrumentid != '':
                rp_obj = rp_obj.filter(instrumentid__contains=instrumentid)
                rp_list = rp_obj.values()
        if stgname != None:
            if stgname != '':
                rp_list = []
                for item in rp_obj:
                    rp_dict = {}
                    rp_dict['ruleid'] = item.ruleid
                    rp_dict['position'] = item.position
                    rp_dict['instrumentid'] = item.instrumentid
                    rp_dict['tradingday'] = item.tradingday
                    stg = Strategy.objects.using('quantWebDB').filter(stgid=item.ruleid)
                    if len(stg) != 0:
                        stgname_filter = stg[0].stgname
                        if stgname in stgname_filter:
                            rp_dict['rulename'] = stgname
                            rp_list.append(rp_dict)
        else:
            rp_list = list(rp_obj.values())

        if ruleid != None:
            if ruleid != '':
                temp_list = []
                for item in rp_list:
                    if ruleid in str(item["ruleid"]):
                        temp_list.append(item)
                rp_list = temp_list

        # 排序 Ruleposition
        for item in rp_list:
            stg_qs = Strategy.objects.using('quantWebDB').filter(stgid=item['ruleid'])
            stgname = ''
            if len(stg_qs) != 0:
                stgname = stg_qs[0].stgname
            item['rulename'] = stgname
        if pflag == "2":
            result_list_sorted = sorted(rp_list, key=itemgetter('tradingday'), reverse=True)
        else:
            result_list_sorted = sorted(rp_list, key=itemgetter('ruleid'), reverse=False)

    if type == '3':
        rm_list = list(rm_obj.values())
        if direction is not None:
            if direction != "":
                rm_obj = rm_obj.filter(direction=direction)
                rm_list = rm_obj.values()
        if legsettltype is not None:
            if legsettltype != "":
                rm_obj = rm_obj.filter(settletype=legsettltype)
                rm_list = rm_obj.values()
        if ruleid is not None:
            if ruleid != "":
                temp_list = []
                for item in rm_obj:
                    if ruleid in str(item.ruleid):
                        item_dict = model_to_dict(item)
                        temp_list.append(item_dict)
                rm_list = temp_list
        if bondid is not None:
            if bondid != "":
                temp_list = []
                for item in rm_obj:
                    if bondid in str(item.bondid):
                        item_dict = model_to_dict(item)
                        temp_list.append(item_dict)
                rm_list = temp_list
        if customerid is not None:
            if customerid != "":
                temp_list = []
                for item in rm_obj:
                    if customerid in str(item.customerid):
                        item_dict = model_to_dict(item)
                        temp_list.append(item_dict)
                rm_list = temp_list
        # 排序 Manaual
        for item in rm_list:
            item['settletype'] = LegSettlType_ModelChoices.get(item['settletype'], None)
            item['direction'] = Direction_ModelChoices.get(item['direction'], None)
            stg_qs = Strategy.objects.using('quantWebDB').filter(stgid=item['ruleid'])
            stgname = ''
            if len(stg_qs) != 0:
                stgname = stg_qs[0].stgname
            item['stgname'] = stgname
            if item.get("transactime") is None:
                item["transactime"] = "-1"
        result_list_sorted = sorted(rm_list, key=itemgetter("transactime"), reverse=True)

    return JsonResponse(result_list_sorted, safe=False)


def search_trans(oowner, stgname, status):
    if oowner:
        if stgname:
            if status:
                trans_list = Transfer.objects.using('quantWebDB').filter(
                    orignalowner__contains=oowner,
                    auditstatus=status,
                    stgname__contains=stgname
                ).all().order_by("-applydatetime")
            else:
                trans_list = Transfer.objects.using('quantWebDB').filter(
                    orignalowner__contains=oowner,
                    stgname__contains=stgname
                ).all().order_by("-applydatetime")
        else:
            if status:
                trans_list = Transfer.objects.using('quantWebDB').filter(
                    orignalowner__contains=oowner,
                    auditstatus=status,
                ).all().order_by("-applydatetime")
            else:
                trans_list = Transfer.objects.using('quantWebDB').filter(
                    orignalowner__contains=oowner,
                ).all().order_by("-applydatetime")
    else:
        if stgname:
            if status:
                trans_list = Transfer.objects.using('quantWebDB').filter(
                    auditstatus=status,
                    stgname__contains=stgname
                ).all().order_by("-applydatetime")
            else:
                trans_list = Transfer.objects.using('quantWebDB').filter(
                    stgname__contains=stgname
                ).all().order_by("-applydatetime")
        else:
            if status:
                trans_list = Transfer.objects.using('quantWebDB').filter(
                    auditstatus=status,
                ).all().order_by("-applydatetime")
            else:
                trans_list = Transfer.objects.using('quantWebDB').all().order_by("-applydatetime")

    if len(trans_list):
        ## 定义两个列表，一个存待审批，另一个存其他审批状态。
        prestatus_list = []
        othstatus_list = []
        for transobj in trans_list:
            transobj.auditstatus = AuditStatus.get(transobj.auditstatus, None)
            if transobj.auditstatus == "待审批":
                prestatus_list.append(transobj)
            else:
                othstatus_list.append(transobj)
        prestatus_list.extend(othstatus_list)
        trlist = prestatus_list
    else:
        trlist = trans_list

    return trlist
